<?php

namespace App\Repository;

use App\Exceptions\BusinessException;
use App\Common\Constant;
use App\Common\ResponseCode;
use App\Models\Common\Tag;
use App\Models\Goods\AttributesValue;
use App\Models\Goods\Category;
use App\Models\Goods\Comment;
use App\Models\Goods\Goods;
use App\Models\Goods\Products;
use App\Models\Goods\Specs;
use App\Params\Backend\GoodsUpdateParam;
use Illuminate\Support\Facades\Log;

/**
 * 商品数据获取类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class GoodsRepository extends BaseRepository
{
    /**
     * 获取商品信息
     *
     * @param int $goodsId
     * @param array $columns
     * @return
     * @throws BusinessException
     */
    public function getById(int $goodsId, array $columns = [])
    {
        try {
            // 获取主商品信息
            $goods = Goods::getById($goodsId, $columns);
            // 获取商品属性
            $goods->attrs = AttributesValue::getGoodsAttrs($goodsId);
            // 获取商品信息
            $goods->products = Products::getByGoodsId($goodsId);
            $goods->platform = json_decode($goods->platform, true);
            $goods->keywords = json_decode($goods->keywords, true);
            $goods->gallery = json_decode($goods->gallery, true);
            $goods->tag_ids = json_decode($goods->tag_ids, true);
            // 发布平台
            $goods->platforms = $this->getPlatform($goods->platform);
            // 标签
            $goods->tags = $this->getTags($goods->tag_ids);
            // 规格
            $goods->spec_list = Specs::getByGoodsId($goodsId);
            return $goods;
        } catch (\Exception $exception) {
            Log::error("[获取商品] {$exception->getMessage()}");
            throw new BusinessException(ResponseCode::GOODS_NOT_FOUND);
        }
    }

    /**
     * 获取商品发布平台
     *
     * @param array $platform
     * @return string
     */
    private function getPlatform(array $platform = [])
    {
        $platforms = '';
        collect($platform)->each(function ($item) use (&$platforms) {
            $platforms .= Constant::GOODS_PLATFORM_MAP[$item] . ';';
        });
        return $platforms;
    }

    /**
     * 获取商品标签
     *
     * @param array $tagIds
     * @return string
     */
    private function getTags(array $tagIds = [])
    {
        $tags = '';
        collect($tagIds)->each(function ($item) use (&$tags) {
            $tags .= Tag::getById($item)->tag_name . ';';
        });
        return $tags;
    }

    /**
     * 获取全路径分类
     *
     * @param int $categoryId
     * @return array
     */
    public function getCategoryIds(int $categoryId)
    {
        $categorys = [];
        $category = Category::query()->where('category_id', $categoryId)->first();
        $path = $category->path;
        if(!empty($path)) {
            $pathList = explode('/', $path);
            foreach ($pathList as $categoryId)
            {
                if(!empty($categoryId)) {
                    $category = Category::query()->where('category_id', $categoryId)->first();
                    $categorys[] = ['category_id' => $category->category_id, 'name' => $category->name];
                }
            }
        }
        return $categorys;
    }

    /**
     * 保存货品信息
     *
     * @param GoodsUpdateParam $data
     * @return int|mixed
     */
    public static function saveData(GoodsUpdateParam $data)
    {
        $goods = $data->getGoodsId() ? Goods::find($data->getGoodsId()) : new Goods();
        foreach ($data as $field => $value) {
            $goods->{$field} = $value;
        }
        return $goods->save() ? $goods->goods_id : 0;
    }

    /**
     * 保存评论
     *
     * @param array $data
     * @return int|mixed
     */
    public function saveComment(array $data)
    {
        $comment = !empty($data['comment_id']) ? Comment::find($data['comment_id']) : new Comment();
        foreach ($data as $field => $value) {
            $comment->{$field} = $value;
        }
        return $comment->save() ? $comment->comment_id : 0;
    }

    /**
     * 获取商品评论列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getCommentList(array $filter = [])
    {
        $query = Comment::query()->orderBy('created_at');
        if(!empty($filter['customer_id'])) {
            $query->where('customer_id', $filter['customer_id']);
        }
        if(!empty($filter['goods_id'])) {
            $query->where('goods_id', $filter['goods_id']);
        }
        if(!empty($filter['product_id'])) {
            $query->where('product_id', $filter['product_id']);
        }
        if(isset($filter['score_type']) && $filter['score_type'] > 0) {
            $query->where('score', $filter['score_type']);
        }
        return $query;
    }
}
